package com.persondemo.videoappliction.ui.tv;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.persondemo.videoappliction.R;
import com.persondemo.videoappliction.bean.MainBean;
import com.persondemo.videoappliction.bean.TvMovieBean;
import com.persondemo.videoappliction.component.ApplicationComponent;
import com.persondemo.videoappliction.component.DaggerHttpComponent;
import com.persondemo.videoappliction.event.GridEvent;
import com.persondemo.videoappliction.ui.adapter.BaseVideoAdapter;
import com.persondemo.videoappliction.ui.adapter.MoiveAgeAdapter;
import com.persondemo.videoappliction.ui.adapter.MoiveTypeAdapter;
import com.persondemo.videoappliction.ui.adapter.MovieCityAdapter;
import com.persondemo.videoappliction.ui.base.BaseActivity;
import com.persondemo.videoappliction.ui.base.BaseFragment;
import com.persondemo.videoappliction.ui.movie.contract.MoiveContract;
import com.persondemo.videoappliction.ui.movie.presenter.MoviePresenter;
import com.persondemo.videoappliction.ui.search.SearchActivity;
import com.persondemo.videoappliction.ui.video.VideoDetilsActivity;
import com.persondemo.videoappliction.utils.AnimationUtil;
import com.persondemo.videoappliction.utils.RxDeviceTool;
import com.persondemo.videoappliction.utils.T;
import com.persondemo.videoappliction.utils.ViewFindUtils;
import com.persondemo.videoappliction.widget.CustomLoadMoreView;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Created by Administrator on 2018/3/21.
 */

public class TvActivity extends BaseActivity<MoviePresenter> implements MoiveContract.View {
    public static final String TAG = "TvActivity";
    @BindView(R.id.rl_tv_type)
    RelativeLayout rlTvType;
    @BindView(R.id.rl_search)
    RelativeLayout rlSearch;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.SimpleMultiStateView)
    com.persondemo.videoappliction.widget.SimpleMultiStateView SimpleMultiStateView;
    @BindView(R.id.mPtrFrameLayout)
    PtrClassicFrameLayout mPtrFrameLayout;
    private RecyclerView recycle_01;
    private RecyclerView recycle_02;
    private RecyclerView recycle_03;
    private MoiveTypeAdapter typeadapter;
    private MoiveAgeAdapter agedapter;
    private MovieCityAdapter citydapter;
    private BaseVideoAdapter baseVideoAdapter;
    private PopupWindow window;

    int fromYDelta;
    List<TvMovieBean.DataBean.TypesListBean> typelist = new ArrayList<>();//tv类型
    List<TvMovieBean.DataBean.AgesListBean> agelist = new ArrayList<>();//地区名字
    List<TvMovieBean.DataBean.CityListBean> citylist = new ArrayList<>();//年代
    List<TvMovieBean.DataBean.DylistBean> dylistBeanList = new ArrayList<>();
    private static final String TYPE = "2";//tv类型
    private String types = "";//电影类型
    private String city = "";//地区名字
    private String ages = "";//年代
    private int page = 1;//页数
    View footview;
    private TextView foot_version;

    @Override
    public int getContentLayout() {
        return R.layout.module_fragment_tv;
    }

    @Override
    public void initInjector(ApplicationComponent appComponent) {
        DaggerHttpComponent.builder()
                .applicationComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void bindView(View view, Bundle savedInstanceState) {
//        EventBus.getDefault().register(this);
        footview=LayoutInflater.from(TvActivity.this).inflate(R.layout.footview,null);
        foot_version=footview.findViewById(R.id.foot_version);
        foot_version.setText("当前版本："+ RxDeviceTool.getVerName(TvActivity.this));
        mPtrFrameLayout.disableWhenHorizontalMove(true);
        mPtrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, mRecyclerView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                page = 1;
                if (mPresenter != null) {
                    types = "";//电影类型
                    city = "";//地区名字
                    ages = "";//年代
                    mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
                }
            }
        });
        mRecyclerView.setLayoutManager(new GridLayoutManager(TvActivity.this, 3));
        baseVideoAdapter = new BaseVideoAdapter(dylistBeanList,TvActivity.this);
        mRecyclerView.setAdapter(baseVideoAdapter);
        baseVideoAdapter.setEnableLoadMore(true);
        baseVideoAdapter.setLoadMoreView(new CustomLoadMoreView());
        baseVideoAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        baseVideoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                gotovideodetils(dylistBeanList.get(position).getId());
            }
        });
        baseVideoAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
            }
        }, mRecyclerView);
    }

    @Override
    public void initData() {
        showLoadingDialog();
        typelist = new ArrayList<>();
        agelist = new ArrayList<>();
        citylist = new ArrayList<>();
        dylistBeanList = new ArrayList<>();
        Intent intent=getIntent();
        if (intent!=null){
            types=intent.getStringExtra("title");
        }
        if (mPresenter != null) {
            mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
            page++;
        }
    }

    private void showpop() {
        View popupView = LayoutInflater.from(TvActivity.this).inflate(R.layout.module_pop_type, null);
        recycle_01 = popupView.findViewById(R.id.recycle_01);
        recycle_02 = popupView.findViewById(R.id.recycle_02);
        recycle_03 = popupView.findViewById(R.id.recycle_03);

        recycle_01.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        recycle_02.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        recycle_03.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        typeadapter = new MoiveTypeAdapter(typelist, TvActivity.this);
        agedapter = new MoiveAgeAdapter(agelist,TvActivity.this);
        citydapter = new MovieCityAdapter(citylist,TvActivity.this);
        recycle_01.setAdapter(typeadapter);
        recycle_02.setAdapter(citydapter);
        recycle_03.setAdapter(agedapter);
        typeadapter.setOnItemActionListener(new MoiveTypeAdapter.OnItemActionListener() {
            @Override
            public void onItemClickListener(View v, int pos) {
                types = typelist.get(pos).getId() + "";
                page = 1;
                if (mPresenter != null) {
                    showLoadingDialog();
                    mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
                }
            }
        });
        agedapter.setOnItemActionListener(new MoiveAgeAdapter.OnItemActionListener() {
            @Override
            public void onItemClickListener(View v, int pos) {
                ages = agelist.get(pos).getAges();
                page = 1;
                if (mPresenter != null) {
                    showLoadingDialog();
                    mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
                }
            }
        });
        citydapter.setOnItemActionListener(new MovieCityAdapter.OnItemActionListener() {
            @Override
            public void onItemClickListener(View v, int pos) {
                city = citylist.get(pos).getCity();
                page = 1;
                if (mPresenter != null) {
                    showLoadingDialog();
                    mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
                }
            }
        });
        window = new PopupWindow(popupView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        window.setBackgroundDrawable(new BitmapDrawable());
        //将这两个属性设置为false，使点击popupwindow外面其他地方会消失
        window.setOutsideTouchable(true);
        window.setFocusable(true);
        //获取popupwindow高度确定动画开始位置
        int contentHeight = ViewFindUtils.getViewMeasuredHeight(popupView);
        window.showAsDropDown(rlTvType, 0, 0);
        fromYDelta = -contentHeight - 50;
        window.getContentView().startAnimation(AnimationUtil.createInAnimation(TvActivity.this, fromYDelta));
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });
    }

    @OnClick({R.id.rl_tv_type, R.id.rl_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_tv_type:
                showpop();
                break;
            case R.id.rl_search:
                startActivity(new Intent(TvActivity.this, SearchActivity.class));
                TvActivity.this.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                break;
        }
    }



//    @Subscriber
//    private void gogrid(GridEvent event) {
//        if (event == null) return;
//        MainBean.DataBean.TypeslistBean bean = event.typeslistBean;
//        types = bean.getId()+"";
//        page = 1;
//        if (mPresenter != null) {
//            mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
//        }
//    }
//
//    @Override
//    protected void onDestroy() {
//        EventBus.getDefault().unregister(this);
//        super.onDestroy();
//    }



    @Override
    public void loaddata(TvMovieBean tvMovieBean) {
        if (tvMovieBean == null) {
            showFaild();
            hideLoadingDialog();
            return;
        }
        if (tvMovieBean.getData().getDylist() == null || tvMovieBean.getData().getDylist().size() == 0) {
            hideLoadingDialog();
            T.showShort(TvActivity.this, "没有更多数据了！");
//            baseVideoAdapter.setEmptyView();
            return;
        }
        if (tvMovieBean.getStatus() == 1) {
            if (tvMovieBean.getData().getTypesList() != null && tvMovieBean.getData().getTypesList().size() > 0) {
//                    typelist.clear();
                typelist = tvMovieBean.getData().getTypesList();

            }
            if (tvMovieBean.getData().getAgesList() != null && tvMovieBean.getData().getAgesList().size() > 0) {
//                    agelist.clear();
                agelist = tvMovieBean.getData().getAgesList();

            }
            if (tvMovieBean.getData().getCityList() != null && tvMovieBean.getData().getCityList().size() > 0) {
//                    citylist.clear();
                citylist = tvMovieBean.getData().getCityList();
            }
            if (tvMovieBean.getData().getDylist() != null && tvMovieBean.getData().getDylist().size() > 0) {
                dylistBeanList.clear();
                baseVideoAdapter.removeAllFooterView();
                dylistBeanList = tvMovieBean.getData().getDylist();
                baseVideoAdapter.setNewData(dylistBeanList);
                mPtrFrameLayout.refreshComplete();
                showSuccess();
                page++;
                hideLoadingDialog();
                if (dylistBeanList.size() < 24) {
                    baseVideoAdapter.loadMoreEnd();
                    baseVideoAdapter.addFooterView(footview);
                }
            }
        } else {
            T.showShort(TvActivity.this, tvMovieBean.getMsg());
        }
    }
    @Override
    public void onRetry() {
        if (mPresenter != null) {
            mPresenter.getdetilsdata(TYPE, types, city, ages, page + "");
        }
    }
    @Override
    public void loaddatamore(List<TvMovieBean.DataBean.DylistBean> dylistBeanList) {
        if (dylistBeanList == null||dylistBeanList.size()==0) {
            baseVideoAdapter.loadMoreEnd();
            baseVideoAdapter.addFooterView(footview);
            T.showShort(TvActivity.this, "没有更多数据了！");
            return;
        } else {
            page++;
            baseVideoAdapter.addData(dylistBeanList);
            baseVideoAdapter.loadMoreComplete();
        }
    }
    private void gotovideodetils(int id) {
        Intent intent = new Intent(TvActivity.this, VideoDetilsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("id", id);
        intent.putExtras(bundle);
        startActivity(intent);
        TvActivity.this.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

}
